package yxy.banana.launcher;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import yxy.apple.util.JSONUtility;

public class JSONBeanConfiguration {

	private static final HashMap<Object, Object> shared = new HashMap<>();

	public static <T> void share(Object key, T bean) {
		shared.put(key, bean);
	}

	@SuppressWarnings("unchecked")
	public static <T> T shared(Object key, Class<T> clazz) {
		Object object = shared.get(key);
		if (object != null) {
			return (T) object;
		} else {
			return null;
		}
	}

	public static <T> T load(String filename, Class<T> clazz) throws IOException {
		return load(filename, "UTF-8", clazz);
	}

	public static <T> T load(File file, Class<T> clazz) throws IOException {
		return load(file, "UTF-8", clazz);
	}

	public static <T> T load(String filename, String encoding, Class<T> clazz) throws IOException {
		return load(new File(filename), encoding, clazz);
	}

	public static <T> T load(File file, String encoding, Class<T> clazz) throws IOException {
		JSONObject json = JSONUtility.read(file, encoding);
		return load(json, clazz);
	}

	public static <T> T load(JSONObject json, Class<T> clazz) throws IOException {
		try {
			return JSON.toJavaObject(json, clazz);
		} catch (Exception e) {
			throw new IOException(e);
		}
	}
}
